package com.ky.facescan.api.rx;

import android.content.Context;
import android.widget.Toast;

import com.google.gson.JsonParseException;
import com.ky.facescan.api.exception.ApiException;
import com.ky.facescan.api.exception.BaseException;
import com.ky.facescan.api.exception.ErrorMessageFactory;


import java.net.SocketException;
import java.net.SocketTimeoutException;

import retrofit2.HttpException;

/**
 * Created by admin on 2018/3/16.
 *
 * @version $Rev$
 * @time 2018/3/16 12:27
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDate $Date$
 * @updateDes ${TODO}
 */

public class RxErrorHandler {

    private Context mContext;

    public RxErrorHandler(Context context) {
        this.mContext = context;
    }

    public BaseException handleError(Throwable e) {

        BaseException exception = new BaseException();

        if (e instanceof ApiException) {
            exception.setCode(((ApiException) e).getCode());
            exception.setDisplayMessage(((ApiException) e).getDisplayMessage());

            /**
             * 此处，因为服务端，已经在返回结果中，给了msg，不需要本地写错误code对应的msg，所以可以直接返回
             * 如果服务端未给msg，则需要在BaseException类中，定义错误提示
             */
            return exception;
        } else if (e instanceof JsonParseException) {
            exception.setCode(BaseException.JSON_ERROR);
        } else if (e instanceof SocketException) {
            exception.setCode(BaseException.SOCKET_ERROR);
        } else if (e instanceof SocketTimeoutException) {
            exception.setCode(BaseException.SOCKET_TIMEOUT_ERROR);
        } else if (e instanceof HttpException) {
            exception.setCode(((HttpException) e).code() + "");
        } else {
            exception.setCode(BaseException.UNKNOWN_ERROR);
        }

        exception.setDisplayMessage(ErrorMessageFactory.create(mContext, exception.getCode()));

        return exception;

    }


    public void showErrorMessage(BaseException e) {
        Toast.makeText(mContext, e.getDisplayMessage(), Toast.LENGTH_LONG).show();
    }


}
